package com.example.fw;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class AccountHelper extends WebDriverHelperBase {

	public AccountHelper(ApplicationManager manager) {
		super(manager);
	}

	public void signup(User user) {
		openUrl("/signup_page.php");
		//click(By.cssSelector("span.bracket-link"));
		type(By.name("username"), user.login);
		type(By.name("email"), user.email);
		click(By.cssSelector("input.button"));
		
		WebElement errorMessage = findElement(By.cssSelector("table.width50 tbody tr td p"));
		if (errorMessage !=null) {
			throw new RuntimeException(errorMessage.getText());
		}

		pause(mailDelay);
		String msg = manager.getMailHelper().getNewMail(user.login, user.password);
		String confirmationLink = getConfirmationLink(msg);
		openAbsoluteUrl(confirmationLink);
		
		type(By.name("password"), user.password);
		type(By.name("password_confirm"), user.password);
		click(By.cssSelector("input.button"));
	}

	public static String getConfirmationLink(String text) {
		Pattern regex = Pattern.compile("http\\S*");
		Matcher matcher = regex.matcher(text);
		if (matcher.find()) {
			return matcher.group();
		} else {
			return "";
		}
	}

	public String loggedUser() {
		WebElement element = findElement(By.cssSelector("td.login-info-left span"));
		return element.getText();
	}

	public void login(User user) {
		openUrl("/");
		type(By.name("username"), user.login);
		type(By.name("password"), user.password);
		click(By.cssSelector("input.button"));
	}
	
	public void loginAsAdmin() {
		User admin = new User()
		.setLogin(adminLogin)
		.setPassword(adminPassword);
		login(admin);
	}
	
	public SortedListOf<String> getMantisUsers() {
	    SortedListOf<String> users = new SortedListOf<String>();
	    openUrl("/manage_user_page.php");
        List<WebElement> rows = driver.findElements(By.xpath("//tr[@class='row-1'or @class='row-2']/td[1]"));
        for (WebElement row : rows) {
        	WebElement cells = row.findElement(By.tagName("a"));
        	users.add(cells.getText());
        }
        return users;
}

	public void deleteMantisUser(User user) {
		openUrl("/manage_user_page.php");
		// find user on the page
		click(By.linkText(user.login));
		//pause(3000);
		click(By.xpath("//input[@value='Delete User']"));
		//pause(3000);
		click(By.xpath("//input[@value='Delete Account']"));
	}
}